﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WingIt
{
    [RevisionControlId("$Id: LocalBlackList.cs 684 2012-08-08 10:09:07Z Chinajade $")]
    public class LocalBlacklist
    { //15Jul2012-03:02UTC chinajade
        public enum Purpose
        {
            Resurrect,
        }

        public static void Blacklist(ulong guid, Purpose purpose, TimeSpan duration)
        {
            Logger.ContractRequires(() => duration >= TimeSpan.Zero, () => "duration >= TimeSpan.Zero");

            blacklist[Tuple.Create(guid, purpose)] = DateTime.Now + duration;
            PurgeExpiredEntries();
        }

        public static bool IsBlacklisted(ulong guid, Purpose purpose)
        {
            DateTime blacklistedUntil;
            var key = Tuple.Create(guid, purpose);

            if (!blacklist.TryGetValue(key, out blacklistedUntil))
                { return (false); }

            // remove expired entries
            bool isEntryValid = (blacklistedUntil >= DateTime.Now);
            if (!isEntryValid)
                { blacklist.Remove(key); }

            return (isEntryValid);
        }

        private static void PurgeExpiredEntries()
        {
            DateTime    now = DateTime.Now;
            var         expiredEntries  = blacklist.Where(b => b.Value < now).ToArray();

            foreach (var entry in expiredEntries)
                { blacklist.Remove(entry.Key); }
        }

        private static Dictionary<Tuple<ulong, Purpose>, DateTime> blacklist   = new Dictionary<Tuple<ulong, Purpose>, DateTime>();
    }
}
